﻿using Common.Logger;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace Common.Web.Authentication
{
    /// <summary>
    /// Token质疑处理程序
    /// </summary>
    public class JwtTokenChallengeHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        /// <summary>
        /// Token质疑处理程序
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <param name="encoder"></param>
        /// <param name="clock"></param>
        public JwtTokenChallengeHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        /// <inheritdoc/>
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            throw new NotImplementedException();
        }
        /// <inheritdoc/>
        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            this.Request.Headers.TryGetValue("Authorization", out StringValues authorization);
            var token = this.Request.GetToken();
            var error = token?.GetTokenError();
            var failObj = FuncResult.Fail(error?.FriendlyMessage ?? "token无效", "0401");
            string message = Json.JsonSerializer.JsonSerialize(failObj, GetJsonSettings());
            if (error != null)
            {
                Response.Headers.Add(error.HeaderName, error.HeaderValue);
            }
            Log<JwtTokenChallengeHandler>.Error($"JsonWebToken无效，{failObj.Message}，{authorization}");
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status401Unauthorized;
            await Response.WriteAsync(message);
        }
        /// <inheritdoc/>
        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            var failObj = FuncResult.Fail("权限不足，请联系管理员", "0403");
            string message = Json.JsonSerializer.JsonSerialize(failObj, GetJsonSettings());
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status403Forbidden;
            await Response.WriteAsync(message);
        }

        private static Newtonsoft.Json.JsonSerializerSettings _settings;
        private static Newtonsoft.Json.JsonSerializerSettings GetJsonSettings()
        {
            if (_settings == null)
            {
                _settings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                };
            }
            return _settings;
        }
    }
}
